package cn.exrick.xboot.flow.service.serviceimpl;

import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.common.utils.SnowFlakeUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.content.entity.HontUser;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.exrick.xboot.flow.entity.*;
import cn.exrick.xboot.flow.mapper.FlowTaskInstanceMapper;
import cn.exrick.xboot.flow.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 任务实例表 服务实现类
 * </p>
 *
 * @author zy
 * @since 2022-08-31
 */
@Service
@Transactional
@Slf4j
public class FlowTaskInstanceServiceImpl extends ServiceImpl<FlowTaskInstanceMapper, FlowTaskInstance> implements IFlowTaskInstanceService {


    @Autowired
    private FlowTaskInstanceMapper flowTaskInstanceMapper;
    @Autowired
    private IFlowNodeinfoService iFlowNodeinfoService;
    @Autowired
    private IFlowHistoryService iFlowHistoryService;
    @Autowired
    private IFlowNodeHandlerService iFlowNodeHandlerService;
    @Autowired
    private IFlowInstanceinfoService iFlowInstanceinfoService;
    @Autowired
    private IFlowTaskHandlerService iFlowTaskHandlerService;
    @Autowired
    private SecurityUtil securityUtil;

    @Override
    public IPage<FlowTaskInstance> selectPage(Page<FlowTaskInstance> page, FlowTaskInstance flowTaskInstance) {
        QueryWrapper<FlowTaskInstance> query = Wrappers.query();
        QueryWrapper<FlowTaskInstance> entityWrapper = getEntityWrapper(query, flowTaskInstance);
        return flowTaskInstanceMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<FlowTaskInstance> selectList(FlowTaskInstance flowTaskInstance) {
        QueryWrapper<FlowTaskInstance> query = Wrappers.query();
        QueryWrapper<FlowTaskInstance> entityWrapper = getEntityWrapper(query, flowTaskInstance);
        return flowTaskInstanceMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<FlowTaskInstance> getEntityWrapper(QueryWrapper<FlowTaskInstance> entityWrapper, FlowTaskInstance flowTaskInstance) {
        //条件拼接

        return entityWrapper;
    }

    @Override
    public FlowTaskInstance getFlowTaskInstanceByFlowInstance(String flowInstanceId){
        QueryWrapper<FlowTaskInstance> query = Wrappers.query();
        query.lambda().eq(FlowTaskInstance::getFlowInstanceId,flowInstanceId)
                .eq(FlowTaskInstance::getDel,false);
        return flowTaskInstanceMapper.selectOne(query);
    }
    @Override
    public Result<Object> addFlowTaskInstance(FlowInstanceinfo flowInstanceinfo,
                                              FlowTemplateinfo flowTemplateinfo, Integer level) {
        String id=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
        FlowTaskInstance flowTaskInstance=new FlowTaskInstance();
        flowTaskInstance.setId(id);
        flowTaskInstance.setFlowInstanceId(flowInstanceinfo.getId());
        List<FlowNodeinfo> flowNodeinfos= iFlowNodeinfoService.selectList(flowTemplateinfo.getId(),flowTemplateinfo.getTemplateVersion(),
                1);
        FlowNodeinfo flowNodeinfo=flowNodeinfos.get(0);
        Integer setpId;
        if(flowTemplateinfo.getIsAbove()==0){
        //TODO 根据角色级别 添加任务时 跳过低于这个级别的审批人节点
            FlowNodeinfo node=   iFlowTaskHandlerService.addFlowTaskHandler( flowNodeinfo,level,
                    flowInstanceinfo.getHontDepartmentId(),id);
         if(node!=null){
            flowTaskInstance.setFlowNodeId(node.getId());
             setpId=node.getSetpId();
         }else {
             log.error("没有对应节点的审核人员:{}",flowInstanceinfo);
             return ResultUtil.error(500,"没有对应节点的审核人员");
         }
        }else {
            flowTaskInstance.setFlowNodeId(flowNodeinfo.getId());
            setpId=flowNodeinfo.getSetpId();
        }

        flowTaskInstanceMapper.insert(flowTaskInstance);
        iFlowHistoryService.addFlowHistory(flowTaskInstance,setpId);
        return ResultUtil.success("");
    }

    @Override
    public Result<Object> approval(String flowInstanceId, String opinion) {
        //TODO 获取当前登录人
        HontUser u = securityUtil.getCurrUser();
        FlowTaskInstance flowTaskInstance= getFlowTaskInstanceByFlowInstance(flowInstanceId);
//        boolean flag=iFlowNodeHandlerService.checkUser(flowTaskInstance.getFlowNodeId(),
//                userid,roleIds);
        boolean flag=iFlowTaskHandlerService.checkUser(flowTaskInstance.getId(),u.getId());
        if(!flag){
            return ResultUtil.error("您没有权限审批此节点");
        }
      //更新当前节点数据
        FlowInstanceinfo flowInstanceinfo=iFlowInstanceinfoService.getById(flowInstanceId);
        FlowHistory flowHistory=
                iFlowHistoryService.getFlowHistoryByTaskId(flowTaskInstance.getId());
        flowHistory.setOpinion(opinion);
        flowHistory.setTaskEndTime(LocalDateTime.now());
        flowHistory.setTaskHandler(u.getId());
        flowHistory.setTaskHandlerName(u.getNickName());
        iFlowHistoryService.updateById(flowHistory);
        //审批完成 将当前节点修改为下一个节点
        FlowNodeinfo flowNodeinfo=
                iFlowNodeinfoService.getById(flowTaskInstance.getFlowNodeId());
        if(!FlowNodeinfo.NODE_TYPE_FINISH.equals(flowNodeinfo.getNodeType())){
            FlowNodeinfo nextFlowNodeinfo=iFlowNodeinfoService.getFlowNodeinfo(flowNodeinfo.getTemplateId(),flowNodeinfo.getTemplateVersion(),flowNodeinfo.getSetpId()+1);
            flowTaskInstance.setFlowNodeId(nextFlowNodeinfo.getId());
            flowTaskInstanceMapper.updateById(flowTaskInstance);
            iFlowTaskHandlerService.updateFlowTaskHandler(flowTaskInstance,
                    flowInstanceinfo.getHontDepartmentId());
            iFlowHistoryService.addFlowHistory(flowTaskInstance,nextFlowNodeinfo.getSetpId());
        }else {

            flowInstanceinfo.setFlowEndTime(LocalDateTime.now());
            flowInstanceinfo.setFlowStatus(FlowInstanceinfo.FLOW_STATUS_FINISH);
            iFlowInstanceinfoService.updateById(flowInstanceinfo);
            flowTaskInstanceMapper.deleteById(flowTaskInstance.getId());
            iFlowTaskHandlerService.deleteByTaskId(flowTaskInstance.getId());
            //TODO 流程结束，调取抄送节点
        }
        return ResultUtil.success("");
    }

}
